<template>
  <view class="content" :style="mix_diyStyle">
    <view class="row b-b">
      <text class="tit">{{ $L('联系人') }}</text>
      <input
        class="input"
        maxlength="25"
        type="text"
        v-model="addressData.memberName"
        :placeholder="$L('请输入收货人姓名')"
        placeholder-class="placeholder_add"
      />
    </view>
    <view class="row b-b">
      <text class="tit">{{ $L('联系电话') }}</text>
      <input
        class="input"
        maxlength="11"
        type="text"
        v-model="addressData.telMobile"
        :placeholder="$L('请输入手机号')"
        placeholder-class="placeholder_add"
      />
    </view>
    <view class="row b-b">
      <text class="tit">{{ $L('所在地区') }}</text>
      <text
        @click="chooseArea"
        :class="
          addressData.addressAll == $L(`请选择所在地区`)
            ? 'input placeholder1'
            : 'input'
        "
      >
        {{ addressData.addressAll }}
      </text>
    </view>
    <view class="row b-b">
      <text class="tit">{{ $L('详细地址') }}</text>
      <input
        class="input"
        type="text"
        v-model="addressData.detailAddress"
        :placeholder="$L('请输入详细地址,建议5～40字')"
        maxlength="40"
        placeholder-class="placeholder_add"
      />
    </view>

    <view class="row default_row">
      <text class="tit">{{ $L('设为默认地址') }}</text>
      <switch
        :checked="addressData.isDefault"
        color="var(--color_main)"
        @change="switchChange"
      />
    </view>
    <button
      class="add_btn flex_row_center_center"
      @click="confirm"
      :style="{ top: windowHeight - 80 + 'px' }"
    >
      {{ $L('提交') }}
    </button>
    <selectAddress
      ref="selectAddress"
      :sel_data="selAddressData"
      @selectAddress="successSelectAddress"
    >
    </selectAddress>
  </view>
</template>

<script>
import selectAddress from '@/components/yixuan-selectAddress/yixuan-selectAddress'
import { mapState, mapMutations } from 'vuex'
export default {
  components: {
    selectAddress
  },
  data() {
    return {
      addressData: {
        memberName: '',
        telMobile: '',
        addressAll: this.$L('请选择所在地区'),
        detailAddress: '',
        isDefault: false,
        addressId: '' //编辑收货地址时的id
      },
      selAddressData: [],
      selAddressDataMatch: {
        pro: { code: '', name: '' },
        cit: { code: '', name: '' },
        dis: { code: '', name: '' }
      },
      windowHeight: '',
      clickEvent: false
    }
  },
  onLoad(option) {
    let title = this.$L('新增收货地址')
    if (this.$Route.query.type === 'edit') {
      title = this.$L('编辑收货地址')
      this.addressData.addressId = this.$Route.query.addressId
      this.getAddressDetail()
    }
    this.manageType = this.$Route.query.type
    setTimeout(()=>{
      uni.setNavigationBarTitle({
        title
      })    
    },0);
    uni.getSystemInfo({
      success: (res) => {
        this.windowHeight = res.windowHeight
      }
    })
  },
  computed: {
    ...mapState(['userInfo', 'addressList'])
  },
  methods: {
    ...mapMutations(['operateAddressData']),
    switchChange(e) {
      this.addressData.isDefault = e.detail.value
    },
    chooseArea() {
      this.$refs.selectAddress.show()
    },
    successSelectAddress(address) {
      //选择成功回调
      this.selAddressDataMatch.pro = address[0]
      this.selAddressDataMatch.cit = address[1].code
        ? address[1]
        : { code: '', name: '' }
      if (address.length == 3) {
        this.selAddressDataMatch.dis = address[2]
      } else {
        this.selAddressDataMatch.dis = { code: '', name: '' }
      }
      this.selAddressData = address
      this.addressData.addressAll = ''
      address.map((item) => {
        this.addressData.addressAll += item.name
      })
    },

    //获取收货地址详情
    getAddressDetail() {
      this.$request({
        url: 'v3/member/front/memberAddress/detail',
        data: {
          addressId: this.addressData.addressId
        },
        method: 'GET'
      })
        .then((res) => {
          if (res.state == 200) {
            let result = res.data
            this.addressData.memberName = result.memberName
            this.addressData.telMobile = result.telMobile
            this.addressData.addressAll = result.addressAll
            this.addressData.detailAddress = result.detailAddress
            this.addressData.isDefault = result.isDefault ? true : false
            this.selAddressData = [
              {
                code: result.provinceCode,
                name: ''
              },
              {
                code: result.cityCode,
                name: ''
              },
              {
                code: result.districtCode,
                name: ''
              }
            ]

            this.selAddressDataMatch.pro.code = result.provinceCode
            this.selAddressDataMatch.cit.code = result.cityCode
            this.selAddressDataMatch.dis.code = result.districtCode

            //初始化地址选择组件
          } else {
            this.$api.msg(res.msg)
          }
        })
        .catch((e) => {
          //异常处理
        })
    },

    //提交
    confirm() {
      let data = this.addressData
      if (this.clickEvent) {
        return
      }
      if (!data.memberName.trim()) {
        this.$api.msg(this.$L('请填写收货人姓名'))
        return
      }

      if (data.memberName.trim().length < 2) {
        this.$api.msg(this.$L('收货人姓名为2~25个字'))
        return
      }
      if (!this.$checkTel(data.telMobile)) {
        return
      }
      if (data.addressAll == this.$L('请选择所在地区')) {
        this.$api.msg(this.$L('请选择所在地区'))
        return
      }

      var patrn = /^[\u4e00-\u9fa5a-zA-Z0-9-]+$/g
      if (!data.detailAddress.trim()) {
        this.$api.msg(this.$L('请填写详细地址'))
        return
      } else if (data.detailAddress.length < 5) {
        this.$api.msg(this.$L('详细地址至少填写5个字'))
        return
      } else if (!patrn.test(data.detailAddress)) {
        this.$api.msg(this.$L('详细地址不能输入特殊字符'))
        return
      }

      this.clickEvent = true
      let param = {}
      param.url = data.addressId
        ? 'v3/member/front/memberAddress/edit'
        : 'v3/member/front/memberAddress/add'
      param.data = {}
      param.data.key = this.userInfo.access_token
      param.data.memberName = data.memberName //收货人

      // param.data.provinceCode = this.selAddressData[0].code; //省份编码
      // param.data.cityCode = this.selAddressData[1].code; //城市编码
      // param.data.districtCode = this.selAddressData[2] ? this.selAddressData[2].code : 0; //区县编码
      param.data.provinceCode = this.selAddressDataMatch.pro.code //省份编码
      param.data.cityCode = this.selAddressDataMatch.cit.code //城市编码
      param.data.districtCode = this.selAddressDataMatch.dis.code
        ? this.selAddressDataMatch.dis.code
        : 0 //区县编码

      param.data.addressAll = data.addressAll //所在地区
      param.data.detailAddress = data.detailAddress //详细地址
      param.data.telMobile = data.telMobile //联系电话
      // #ifdef MP-TOUTIAO
      param.data.telMobile = data.telMobile.substring(0, 11)
      // #endif
      param.data.isDefault = data.isDefault ? 1 : 0 //是否设为默认地址（0非默认地址 1默认地址）
      if (data.addressId) {
        param.data.addressId = data.addressId
      }
      param.method = 'POST'
      this.$request(param).then((res) => {
        this.$api.msg(res.msg)
        if (res.state == 200) {
          //更新上一页的数据
          const pages = getCurrentPages() //当前页面栈
          if (pages.length > 1) {
            const beforePage = pages[pages.length - 2] //获取上一个页面实例对象
            beforePage.$vm.getAddressList() //触发上个面中的方法获取地址列表的方法
          }
          setTimeout(() => {
            this.$Router.back(1)
          }, 800)
        } else {
          //错误提示
          this.clickEvent = false
          this.$api.msg(res.msg)
        }
      })
    }
  }
}
</script>

<style lang="scss">
page {
  background: $bg-color-split;
  padding-top: 20rpx;
  width: 750rpx;
  margin: 0 auto;
}

.content {
  position: relative;
}

button::after {
  border: none;
}

.b_b {
  &:after {
    position: absolute;
    z-index: 3;
    left: 20rpx;
    right: 0;
    height: 0;
    content: '';
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  }
}

.row {
  display: flex;
  align-items: center;
  position: relative;
  padding: 0 30rpx;
  height: 100rpx;
  background: #fff;

  &.b-b {
    &:after {
      position: absolute;
      z-index: 3;
      left: 20rpx;
      right: 0;
      height: 0;
      content: '';
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    }
  }

  .tit {
    flex-shrink: 0;
    width: 130rpx;
    font-size: 28rpx;
    color: #333;
  }

  .input {
    flex: 1;
    font-size: 26rpx;
    color: #333;
    font-weight: 600;
  }
}

.default_row {
  margin-top: 20rpx;

  .tit {
    flex: 1;
  }

  switch {
    transform: translateX(16rpx) scale(0.9);
  }
}

.add_btn {
  position: absolute;
  font-size: 34rpx;
  color: #fff !important;
  width: 668rpx;
  height: 88rpx;
  background: var(--color_main_bg);
  border-radius: 44rpx;
  right: 0;
  left: 0;
  margin: 0 auto;
}

.placeholder1 {
  color: #949494 !important;
  font-size: 28rpx !important;

  font-weight: 600;
}

.placeholder_add {
  color: #949494;
}
</style>
